def convert_markdown_headings(md_content, base_prefix="3.1.1"):
    """
    根据基础前缀动态编号Markdown标题

    :param md_content: Markdown文档内容
    :param base_prefix: 基础编号前缀，如"3.1.1"
    :return: 转换后的文档内容
    """
    # 解析基础前缀
    prefix_parts = base_prefix.split('.')

    # 初始化计数器
    level1_counter = int(prefix_parts[-1]) if prefix_parts else 1
    level2_counter = 1
    level3_counter = 1
    level4_counter = 1

    # 获取基础前缀的前部分
    base_str = '.'.join(prefix_parts[:-1]) + '.' if len(prefix_parts) > 1 else ""

    # 按行处理文档
    lines = md_content.split('\n')
    output_lines = []

    for line in lines:
        # 处理一级标题
        if line.startswith('# '):
            # 生成编号：base_str + level1_counter
            new_title = f"{base_str}{level1_counter} {line[2:].strip()}"
            output_lines.append(new_title)
            level1_counter += 1
            level2_counter = 1  # 重置二级计数器
            continue

        # 处理二级标题
        if line.startswith('## '):
            # 生成编号：base_str + level1_counter-1 + '.' + level2_counter
            new_title = f"{base_str}{level1_counter}.{level2_counter} {line[3:].strip()}"
            output_lines.append(new_title)
            level2_counter += 1
            level3_counter = 1  # 重置三级计数器
            continue

        # 处理三级标题
        if line.startswith('### '):
            # 生成编号：base_str + level1_counter-1 + '.' + level2_counter-1 + '.' + level3_counter
            new_title = f"{base_str}{level1_counter}.{level2_counter - 1}.{level3_counter} {line[4:].strip()}"
            output_lines.append(new_title)
            level3_counter += 1
            level4_counter = 1  # 重置四级计数器
            continue

        # 处理四级标题
        if line.startswith('#### '):
            # 生成编号：base_str + level1_counter-1 + '.' + level2_counter-1 + '.' + level3_counter-1 + '.' + level4_counter
            new_title = f"{base_str}{level1_counter}.{level2_counter}.{level3_counter}.{level4_counter} {line[5:].strip()}"
            output_lines.append(new_title)
            level4_counter += 1
            continue
        # 其他行直接保留
        output_lines.append(line)
    # 返回转换后的文档
    return '\n'.join(output_lines)


# 示例使用
if __name__ == "__main__":
    # 原始Markdown内容
    with open('D:\\hbyt\\AI智能投标\\markdown_output\\EHS保障体系_v1.0_2211\\EHS保障体系_v1.0_2211.md', 'r', encoding='utf-8') as f:
        md_content = f.read()
    # 用户输入基础编号
    user_input = input("请输入基础编号前缀 (如 3.1.1): ") or "3.1.1"
    # 转换标题
    converted_content = convert_markdown_headings(md_content, user_input)
    # 打印转换结果
    print("\n转换后的Markdown文档:")
    print("=" * 80)
    print(converted_content)
    # 保存到文件
    output_file = f"converted_EHS_{user_input.replace('.', '_')}.md"
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(converted_content)
    print(f"\n文档已保存为 {output_file}")
